package com.vanzo.service;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.Tpplication;
import com.vanzo.encryption.ByteUtil;
import com.vanzo.encryption.Encryption;
import com.vanzo.encryption.R;
import com.vanzo.instruction.AT;
import com.vanzo.instruction.Instruction;
import com.vanzo.nfc.NFCManager;
import com.vanzo.ui.BaseActivity;
import com.vanzo.util.LogUtil;

/**
 * Created by tisen on 2018/3/5.
 */

public class TestActivity extends BaseActivity implements View.OnClickListener {

    public static final String TAG = "TestActivity";

    private PttKeyReceiver pttKeyReceiver;
    private PowerReceiver powerReceiver;
    private IntentFilter pttKeyFilter;
    private IntentFilter powerFilter;
    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock;

    private Instruction instruction;

    private TextView console;
    private Button power;
    private boolean powerState;

    NFCManager nfcMger;
    private Talkie talkie;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_instruction_test);
        instruction = ((Tpplication) getApplication()).getInstruction();
        talkie = ((Tpplication) getApplication()).getTalkie();
        console = (TextView) findViewById(R.id.talkie_console);
        power = (Button) findViewById(R.id.ins_test_power);
        power.setVisibility(View.INVISIBLE);
        findViewById(R.id.ins_test_con).setOnClickListener(this);
        findViewById(R.id.ins_test_discon).setOnClickListener(this);
        findViewById(R.id.ins_test_switch).setVisibility(View.INVISIBLE);
        findViewById(R.id.ins_test_ptt_on).setVisibility(View.INVISIBLE);
        findViewById(R.id.ins_test_ptt_off).setVisibility(View.INVISIBLE);
        findViewById(R.id.ins_test_pw).setVisibility(View.INVISIBLE);
        findViewById(R.id.ins_test_freq).setVisibility(View.INVISIBLE);
        findViewById(R.id.ins_test_version).setVisibility(View.INVISIBLE);

        nfcMger = new NFCManager(this);

        power.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.put(this, "power", LogUtil.WARN);
                if (!powerState) {
                    instruction.connect();
                } else {
                    instruction.disconnect();
                }
                powerState = !powerState;
                power.setText("电位:" + powerState);
            }
        });
        instruction.setConsole(new Instruction.Console() {
            @Override
            public void onConsole(String result) {
                Message message = new Message();
                message.obj = result;
                consoleHandler.sendMessage(message);
            }
        });
        initWakeAndReceiver();
    }

    private Handler consoleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String con = (String) msg.obj;
            if (con.startsWith("AT+")) {
                console.append("\r\n");
                console.append("\r\n send | " + con);
            } else {
                console.append("\r\n rece | " + con);
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
//        instruction.start();
        powerState = instruction.isPower();
        power.setText("电位:" + powerState);
    }


    @Override
    protected void onResume() {
        super.onResume();
        try {
            nfcMger.verifyNFC();
        } catch (NFCManager.NFCNotSupported nfcnsup) {
            Toast.makeText(this, "nfc not supportecd", Toast.LENGTH_SHORT).show();
        } catch (NFCManager.NFCNotEnabled nfcnEn) {
            Toast.makeText(this, "nfc not enable", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        stopReceiver();
        instruction.disconnect();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ins_test_con:
//                talkie.sendMessage(AT.DMO_CONNECT);
                break;
            case R.id.ins_test_discon:
//                talkie.sendMessage(AT.DMO_DISCONNECT);
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Encryption.NFC binary = nfcMger.readBinaryFromTag(intent);
        if (binary != null) {
            console.append("\r\n binary = " + binary.toString());
//            talkie.sendMessage(AT.DMO_BINARY + "=" + ByteUtil.byteArrayToBit(binary.getBinary(), binary.getLength()));
        }
    }

    private void initWakeAndReceiver() {
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        pttKeyReceiver = new PttKeyReceiver();
        pttKeyFilter = new IntentFilter();
//        pttKeyFilter.addAction(PttKeyReceiver.ACTION_PTT_DOWN);
//        pttKeyFilter.addAction(PttKeyReceiver.ACTION_PTT_UP);

        powerReceiver = new PowerReceiver();
        powerFilter = new IntentFilter();
        powerFilter.addAction(PowerReceiver.ACTION_POWER_OFF);
        powerFilter.addAction(PowerReceiver.ACTION_POWER_ON);
        startReceiver();
    }

    private void startReceiver() {
        wakeLock.acquire();
        registerReceiver(pttKeyReceiver, pttKeyFilter);
        registerReceiver(powerReceiver, powerFilter);
    }

    private void stopReceiver() {
        wakeLock.release();
        if (pttKeyReceiver != null) {
            pttKeyReceiver.unbind();
            unregisterReceiver(pttKeyReceiver);
        }
        if (powerReceiver != null) {
            unregisterReceiver(powerReceiver);
        }
    }

}
